package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

//用户操作
@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;
    @Reference
    private RoleService roleService;
    //获得当前登录用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername(){
        //当spring完成认证时,会将当前用户信息保存到安全框架提供的上下文对象，底层基于session
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(user);
        if (user!=null){
            String username = user.getUsername();
            return new Result(true,MessageConstant.GET_USERNAME_SUCCESS,username);
        }
        return new Result(false,MessageConstant.GET_USERNAME_FAIL);
    }

    //获取用户信息
    @RequestMapping("/findAll")
    public PageResult findAll(@RequestBody QueryPageBean queryPageBean){

        PageResult pageResult = userService.pageQuery(queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString());
        return pageResult;
    }

    //菜单初始化
    @RequestMapping("/getMenuList")
    public Result getMenuList(){
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        try {
            Collection<GrantedAuthority> authorities = user.getAuthorities();
            Set<Menu> menuSet = new HashSet<>();
            for (GrantedAuthority authority : authorities) {
                if("ROLE".equals(authority.getAuthority().split("_")[0])){
                    //获取菜单集合
                    Set<Menu> menus = userService.getMenus(authority.getAuthority());
                    menuSet.addAll(menus);
                }
            }
            //循环添加子级菜单
            for (Menu menu : menuSet) {
                //List<Menu> childMenus = new ArrayList<>();
                Set<Menu> childMenus = new TreeSet<>();
                for (Menu childMenu : menuSet) {
                    if(menu.getId()==childMenu.getParentMenuId()){
                        childMenus.add(childMenu);
                    }
                }
                List list = new ArrayList(childMenus);
                menu.setChildren(list);
            }

            //响应的菜单集合
            Set<Menu> menuResult = new TreeSet<>();
            for (Menu menu : menuSet) {
                if(menu.getParentMenuId()==null){
                    menuResult.add(menu);
                }
            }

            return new Result(true,"菜单初始化成功",menuResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"菜单初始化失败");
        }
    }
/**************************************************************************************/
    //保存用户以及与角色的关联关系
    @RequestMapping("/saveUserAndRole")
    public Result save(@RequestBody com.itheima.pojo.User user, Integer[] roleIds){
        //密码转换
        String pwd = encryptPassword(user.getPassword());
        user.setPassword(pwd);
        try {
            userService.saveUserAndRole(user,roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"新建失败");
        }
        return new Result(true,"新建成功");
    }

    //删除选中id用户
    @RequestMapping("/delete")
    public Result delete(Integer id){
        return userService.delete(id);
    }

    //回显用户数据
    @RequestMapping("/findById")
    public Result findById(Integer id){
        Result result =new Result(true,"用户数据回显成功");
        try {
            com.itheima.pojo.User user=userService.findById(id);
            result.setData(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"用户数据回显失败");
        }
        return result;
    }
    //回显用户与角色的关联关系
    @RequestMapping("/getUserAndRole")
    public Result getUserAndRole(Integer id){
        Result result =new Result(true,"关联关系数据回显成功");
        try {
            List<Integer> roleIds=userService.getUserAndRole(id);
            result.setData(roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"关联关系数据回显失败");
        }
        return result;
    }

    //修改用户与角色的关联关系
    @RequestMapping("edit")
    public Result edit(@RequestBody com.itheima.pojo.User user,Integer[] roleIds){
        Result result =new Result(true,"修改成功");
        try {
            //密码转换
            if(user.getPassword().length()<=12){
                String pwd = encryptPassword(user.getPassword());
                user.setPassword(pwd);
            }
            userService.edit(user,roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"修改失败");
        }
        return result;
    }

    //查询所有角色信息
    @RequestMapping("findAllRole")
    public Result findAllRole(){
        Result result = new Result(true, "获取角色成功");
        try {
            List<Role> roles = roleService.findAll();
            result.setData(roles);
        } catch (Exception e) {
            e.printStackTrace();
            new Result(false,"获取角色失败");
        }
        return result;
    }

    //密码加密
    private String encryptPassword(String password) {
        // BCryptPasswordEncoder 加密
        return new BCryptPasswordEncoder().encode(password);
    }

    //权限验证内容初始化
    @RequestMapping("/permissionShow")
    public Result permissionShow(String moduleName){
        Map resultMap = new HashMap();
        resultMap.put("ADD",true);
        resultMap.put("DELETE",true);
        resultMap.put("EDIT",true);
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        try {
            Collection<GrantedAuthority> authorities = user.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                //System.out.println(authority.getAuthority());
                if((moduleName+"_ADD").equals(authority.getAuthority())){
                    resultMap.put("ADD",false);
                }
                if((moduleName+"_DELETE").equals(authority.getAuthority())){
                    resultMap.put("DELETE",false);
                }
                if((moduleName+"_EDIT").equals(authority.getAuthority())){
                    resultMap.put("EDIT",false);
                }
            }
            return new Result(true,"权限初始化成功",resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"权限初始化失败");
        }
    }

    @RequestMapping("setpassword")
    public Result setpassword(@RequestBody com.itheima.pojo.User user){
        Result result =new Result(true,"修改成功");
        try {
            //密码转换
            String pwd = encryptPassword(user.getPassword());
            user.setPassword(pwd);
            userService.setpassword(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"修改失败");
        }
        return result;
    }
}
